<template>
  <div class="admin-list-container">
    <!-- 搜索区域 -->
    <el-form inline class="search-form">
      <el-form-item label="管理员姓名">
        <el-input v-model="searchParams.name" placeholder="请输入管理员姓名" clearable @clear="fetchAdminData"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchAdminData">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="handleAdd">新增管理员</el-button>
      </el-form-item>
    </el-form>

    <!-- 管理员列表表格 -->
    <el-table :data="adminList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" width="150" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" width="150" align="center"></el-table-column>
      <el-table-column prop="phone" label="电话" width="150" align="center"></el-table-column>
      <el-table-column prop="sex" label="性别" width="100" align="center"></el-table-column>
      <el-table-column prop="idNumber" label="身份证号" width="200" align="center"></el-table-column>
      <el-table-column label="状态" width="150" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" class="delete-btn" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total"></el-pagination>

    <!-- 新增管理员信息的对话框 -->
    <el-dialog title="新增管理员信息" :visible.sync="addDialogVisible" width="50%">
      <el-form :model="addForm" label-width="100px" ref="addForm" :rules="addFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="addForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="addForm.idNumber"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑管理员信息的对话框 -->
    <el-dialog title="编辑管理员信息" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" label-width="100px" ref="editForm" :rules="editFormRules">
        <el-form-item label="ID" prop="id">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="editForm.idNumber"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request"
export default {
  data() {
    return {
      searchParams: {
        name: "",
        page: 1,
        pageSize: 10,
      },
      adminList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      editDialogVisible: false,
      addDialogVisible: false,
      editForm: {
        id: null,
        name: "",
        username: "",
        password: "",
        phone: "",
        sex: "",
        idNumber: "",
      },
      addForm: {
        username: "",
        name: "",
        phone: "",
        sex: "",
        idNumber: "",
      },
      editFormRules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        idNumber: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
      },
      addFormRules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        idNumber: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
      },
    };
  },
  created() {
    this.fetchAdminData();
  },
  methods: {
    // 获取管理员数据
    fetchAdminData() {
      this.loading = true;
      this.searchParams.page = this.currentPage;
      this.searchParams.pageSize = this.pageSize;

      request
        .get("/admin/admin/pageSearch", { params: this.searchParams })
        .then((response) => {
          console.log(response.code)
          if (response && response.code === 1) {
            this.adminList = response.data.records || [];
            this.total = response.total || 0;
          } else {
            this.$message.error("获取管理员数据失败：" + data.message);
          }
        })
        .catch((error) => {
          console.error("获取管理员数据失败：", error);
          this.$message.error("获取管理员数据失败：" + error.message);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleStatusChange(row) {
      const status = row.status;
      const id = row.id;

      console.log("ID:", id); // 打印 ID
      console.log("Status:", status); // 打印 Status

      request
        .post(`/admin/admin/status/${status}`, null, { params: { id } })
        .then((response) => {
          if (response && response.code === 1) {
            this.$message.success("状态修改成功");
          } else {
            this.$message.error("状态修改失败：" + data.message);
            // 如果修改失败，恢复原来的状态
            row.status = status === 1 ? 0 : 1;
          }
        })
        .catch((error) => {
          console.error("状态修改失败：", error);
          this.$message.error("状态修改失败：" + error.message);
          // 如果修改失败，恢复原来的状态
          row.status = status === 1 ? 0 : 1;
        });
    },
    // 新增管理员
    handleAdd() {
      this.addForm = {
        username: "",
        name: "",
        phone: "",
        sex: "",
        idNumber: "",
      };
      this.addDialogVisible = true;
    },
    // 提交新增
    submitAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          request
            .post("/admin/admin/create", this.addForm)
            .then((response) => {
              if (response && response.code === 1) {
                this.$message.success("管理员新增成功");
                this.addDialogVisible = false;
                this.fetchAdminData(); // 刷新列表
              } else {
                this.$message.error("管理员新增失败：" + data.message);
              }
            })
            .catch((error) => {
              console.error("管理员新增失败：", error);
              this.$message.error("管理员新增失败：" + error.message);
            });
        } else {
          this.$message.error("表单验证失败，请检查输入");
        }
      });
    },
    // 编辑管理员
    handleEdit(row) {
      this.editForm = { ...row };
      this.editDialogVisible = true;
    },
    // 提交编辑
    submitEdit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          request
            .put("/admin/admin/update", this.editForm)
            .then((response) => {
              if (response && response.code === 1) {
                this.$message.success("管理员信息更新成功");
                this.editDialogVisible = false;
                this.fetchAdminData(); // 刷新列表
              } else {
                this.$message.error("管理员信息更新失败：" + data.message);
              }
            })
            .catch((error) => {
              console.error("管理员信息更新失败：", error);
              this.$message.error("管理员信息更新失败：" + error.message);
            });
        } else {
          this.$message.error("表单验证失败，请检查输入");
        }
      });
    },
    // 删除管理员
    handleDelete(row) {
      this.$confirm("此操作将永久删除该管理员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          request
            .delete(`/admin/admin/delete/${row.id}`)
            .then((response) => {
              if (response && response.code === 1) {
                this.$message.success("管理员删除成功");
                this.fetchAdminData(); // 刷新列表
              } else {
                this.$message.error("管理员删除失败：" + data.message);
              }
            })
            .catch((error) => {
              console.error("管理员删除失败：", error);
              this.$message.error("管理员删除失败：" + error.message);
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 分页大小改变
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchAdminData();
    },
    // 当前页码改变
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchAdminData();
    },
    // 格式化状态
    formatStatus(row, column, cellValue) {
      if (cellValue === 0) {
        return "禁用";
      } else if (cellValue === 1) {
        return "启用";
      } else {
        return "未知";
      }
    },
  },
};
</script>

<style scoped>
.admin-list-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.delete-btn {
  color: #f56c6c;
}
</style>